***********************************************
**************** ISSUANCES DATA ***************
***********************************************
/*
In this do file, we import and prepare the data on
issuances and study the correlations with fiscal vars.

*/

*----------------
* PATHS
*----------------
global replication `c(pwd)'
global data "$replication\Data"
global inter "$replication\Dta - Intermediate"
global final "$replication\Dta - Final"
global graphs "$replication\Graphs"

clear all
use "$final\AuctionsData.dta", clear

*================
* HOUSEKEEPING
*================
drop iss_yr
drop rmon2mat

*====================================
* AVERAGE MATURITY - QUARTERLY FREQ.
*====================================
gen qy = iss_qy
drop if qy==.

preserve
collapse (sum) totalot_ngdp, by(qy)
rename totalot_ngdp totalot_ngdp_quarterly
save "$inter\aux_file.dta", replace
restore

* Here we merge the average maturity information with the auctions data
merge m:1 qy using "$inter\aux_file.dta"
drop _merge
erase "$inter\aux_file.dta"

*==========================================
* WEIGHT OF ISSUANCES/TOTAL ISSUED (Q-FREQ)
*==========================================
gen weight = totalot_ngdp/totalot_ngdp_quarterly
* Average maturity contribution of that particular issuance
gen term   = mon2mat*weight
preserve

* Here we sum all the contributions to compute the average maturity
collapse (sum) term, by(qy)
rename term avg_mat_quarterly
label var avg_mat_quarterly "Average Maturity Quarterly"
save "$inter\aux_file.dta", replace
restore

merge m:1 qy using "$inter\aux_file.dta"
drop _merge

save "$final\AuctionsQuarterlyAggregation_v2.dta", replace

*==========================================
* CORRELATIONS WITH FISCAL VARIABLES
*==========================================
clear all 

* Spanish macroeconomic statistics
use "$data\SpainCoreStats_Quarterly.dta"

* Spanish yield data
merge 1:1 qy using "$inter\ESP_DNSS_QuarterlyData.dta"
drop _merge

* Merge with the information on average maturity (quarterly)
merge 1:1 qy using "$inter\aux_file.dta",
drop _merge

save "$final\Average_Maturity_Final_Data.dta", replace 
